import '../model/userLoginModel.dart' show UserLoginModel;
import '../model/userModel.dart' show UserModel;
import 'package:pacsun/constants/apiConstants.dart' show ApiConstants;
import '../model/apiResponse.dart';
import 'base/apiClient.dart';

class UserService {
  final ApiClient _apiClient = ApiClient();

  // POST
  Future<UserModel> login(UserLoginModel loginData) async {
    try {
      String uri = '/api/v1/user/login';

      // 准备请求数据
      final requestData = loginData.toJson();

      final response = await _apiClient.post(uri,
          data: requestData, headers: ApiConstants.jsonHeaders);

      final apiResponse = ApiResponse<Map<String, dynamic>>.fromJson(
          response.data, (data) => data as Map<String, dynamic>);

      if (apiResponse.isSuccess && apiResponse.data != null) {
        return UserModel.fromJson(apiResponse.data!);
      } else {
        // throw Exception('${apiResponse.message}');
        throw 'Login failed.';
      }
    } catch (e) {
      print('=== 请求失败 ===');
      print('Error: $e');
      print('==============');
      throw Exception('$e');
    }
  }

  Future<UserModel> getUserInfo(int userId) async {
    try {
      String uri = '/api/v1/user/$userId';

      // 准备请求数据
      //final requestData = loginData.toJson();

      final response =
          await _apiClient.get(uri, headers: ApiConstants.formHeaders);

      final apiResponse = ApiResponse<Map<String, dynamic>>.fromJson(
          response.data, (data) => data as Map<String, dynamic>);

      if (apiResponse.isSuccess && apiResponse.data != null) {
        return UserModel.fromJson(apiResponse.data!);
      } else {
        // throw Exception('${apiResponse.message}');
        throw 'Login failed, please check your username and password.';
      }
    } catch (e) {
      print('=== 请求失败 ===');
      print('Error: $e');
      print('==============');
      throw Exception('$e');
    }
  }

  Future<String?> registerCreator(UserModel userData) async {
    try {
      String uri = '/api/v1/user/save';

      // Prepare targeted request data (only needed fields)
      final requestData = {
        'id': userData.id,
        'aid': userData.aid,
        'fullName': userData.fullName,
        'phone': userData.phone,
        'email': userData.email,
        'birthday': userData.birthday,
        // followers
        'mediaType': userData.mediaType,
        'followers': userData.followers ?? 0,

        'youAre': userData.youAre ?? '',
        'openId': userData.openId,
      };

      final response = await _apiClient.post(
        uri,
        data: requestData,
        headers: ApiConstants.jsonHeaders,
      );

      final apiResponse = ApiResponse<Map<String, dynamic>>.fromJson(
        response.data,
        (data) => data as Map<String, dynamic>,
      );

      if (apiResponse.isSuccess) {
        return 'Congratulations! Registered creator successfully.';
      } else {
        throw 'Failed to register creator: ${apiResponse.message}"}';
      }
    } catch (e) {
      print('=== 请求失败 ===');
      print('Error: $e');

      print('==============');
      throw Exception('$e');
    }
  }

  Future<String?> updateProfile(
      Map<String, dynamic> updatedData, int? taskId) async {
    try {
      String uri = '/api/v1/user/saveNew';

      // Prepare targeted request data (only needed fields)
      final requestData = {
        'id': updatedData['id'],
        'aid': updatedData['aid'],
        'imageUrl': updatedData['imageUrl'],
        'nickName': updatedData['nickname'],
        'bio': updatedData['bio'],
        'birthday': updatedData['dob'],
        'youAre': updatedData['youAre'],
        'mediaType': updatedData['mediaType'],
        'openId': updatedData['openId'],
        'taskCountId': taskId ?? ''
      };

      print('updatedData: ${updatedData}');

      final response = await _apiClient.post(
        uri,
        data: requestData,
        headers: ApiConstants.jsonHeaders,
      );

      final apiResponse = ApiResponse<Map<String, dynamic>>.fromJson(
        response.data,
        (data) => data as Map<String, dynamic>,
      );

      if (apiResponse.isSuccess) {
        return 'Congratulations! Update profile successfully.';
      } else {
        throw 'Failed to update profile ${apiResponse.message}"}';
      }
    } catch (e) {
      print('=== 请求失败 ===');
      print('Error: $e');

      print('==============');
      throw Exception('$e');
    }
  }

  Future<String?> updatePutStore(
      Map<String, dynamic> updatedData, int? taskId) async {
    try {
      String uri = '/api/v1/user/putStorefrontLinkToSocialMedia';

      // Prepare targeted request data (only needed fields)
      final requestData = {
        // 'id': updatedData['id'],
        'aid': updatedData['aid'],
        'imageUrl': updatedData['imageUrl'],
        // 'nickName': updatedData['nickname'],
        // 'bio': updatedData['bio'],
        // 'birthday': updatedData['dob'],
        // 'youAre': updatedData['youAre'],
        // 'mediaType': updatedData['mediaType'],
        // 'openId': updatedData['openId'],
        'taskCountId': taskId ?? ''
      };

      print('updatedData: ${updatedData}');

      final response = await _apiClient.post(
        uri,
        data: requestData,
        headers: ApiConstants.jsonHeaders,
      );

      final apiResponse = ApiResponse<Map<String, dynamic>>.fromJson(
        response.data,
        (data) => data as Map<String, dynamic>,
      );

      if (apiResponse.isSuccess) {
        return 'Congratulations! Update profile successfully.';
      } else {
        throw 'Failed to update profile ${apiResponse.message}"}';
      }
    } catch (e) {
      print('=== 请求失败 ===');
      print('Error: $e');

      print('==============');
      throw Exception('$e');
    }
  }
}
